package com.example.libowu.musicplayer;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;

import static android.app.PendingIntent.FLAG_CANCEL_CURRENT;

/**
 * Created by libowu on 17-12-12.
 */

public class PlayServer extends Service implements Runnable{
    private boolean isStart=true;
    private StartPlay startPlay;
    static boolean isNext=true;
    private RemoteViews remoteViews;
    private NotficationStop no;
    private NotificationManager notificationManager;
    private Notification notification;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        startPlay=new StartPlay();
        return startPlay;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void run() {
        while (isStart){

        }
    }

    public class StartPlay extends Binder{
        private Context context;
        private int p_o;

        public void player(String musicPath){
            no=new NotficationStop();
            IntentFilter nt=new IntentFilter();
            nt.addAction("NOTIFICATION_ISSTOP");
            registerReceiver(no,nt);

            SharedPreferences sharedPreferences=getSharedPreferences("playWay", AppCompatActivity.MODE_PRIVATE);
            p_o=sharedPreferences.getInt("playWay",0);

            Log.e("播放音乐中",">>>>>>>>>>");
            try {
                try{
                    MainActivity.mediaPlayer.stop();
                    MainActivity.mediaPlayer.reset();
                }catch (NullPointerException e){
                    MainActivity.mediaPlayer=new MediaPlayer();
                }
                MainActivity.mediaPlayer=new MediaPlayer();
                MainActivity.mediaPlayer.setDataSource(musicPath);
                MainActivity.mediaPlayer.prepare();
                MainActivity.mediaPlayer.start();

            } catch (IOException e) {
                Log.e("Io异常","IOyichang");
                e.printStackTrace();
            }catch (NullPointerException e){
                Log.e("Null","NullPoint");
                e.printStackTrace();
            }


            //歌曲播放完毕时的动作
            MainActivity.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    SharedPreferences sharedPreferences=getSharedPreferences("playWay", AppCompatActivity.MODE_PRIVATE);
                    p_o=sharedPreferences.getInt("playWay",1);
                            switch (p_o){
                                case 1:
                                    try {
                                        if (MainActivity.sendPosition<MainActivity.list.size()){
                                            ++MainActivity.sendPosition;
                                        }else {
                                            MainActivity.sendPosition=0;
                                        }
                                        MainActivity.mediaPlayer.setDataSource(MainActivity.list.get(MainActivity.sendPosition).getSongPath());
                                        MainActivity.mediaPlayer.prepareAsync();
                                        MainActivity.mediaPlayer.start();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }catch (Exception e){
                                        Log.e("Exception","异常");
                                    }
                                    Log.e("加载if","case1");
                                    break;
                                case 2:
                                    double p=Math.random()*MainActivity.list.size();
                                    MainActivity.sendPosition=(int)p;
                                    try {
                                        MainActivity.mediaPlayer.reset();
                                        MainActivity.mediaPlayer.setDataSource(MainActivity.list.get(MainActivity.sendPosition).getSongPath());
                                        MainActivity.mediaPlayer.prepare();
                                        MainActivity.mediaPlayer.start();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    Log.e("加载if","case2");
                                    break;
                                case 3:
                                    Log.e("加载if","case3");
                                    MainActivity.mediaPlayer.setLooping(true);
                                    break;
                                default:
                                    break;
                            }
                        setNotification(MainActivity.list.get(MainActivity.sendPosition).getSongN(),MainActivity.list.get(MainActivity.sendPosition).getSongImgPath());
                        Intent intent=new Intent();
                        intent.setAction("MUSIC_CHANGE");
                        intent.putExtra("musicName",MainActivity.list.get(MainActivity.sendPosition).getSongN());
                        sendBroadcast(intent);
                }
            });
            setNotification(MainActivity.list.get(MainActivity.sendPosition).getSongN(),MainActivity.list.get(MainActivity.sendPosition).getSongImgPath());

        }

        public void setNotification(String sN,Uri songImgPath) {
            notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notification=new Notification();
            notification.icon=R.drawable.ico;
            notification.when=System.currentTimeMillis();
            Intent intent=new Intent(context,MusicInterface.class);
            remoteViews=new RemoteViews(getPackageName(),R.layout.notification);
            remoteViews.setTextViewText(R.id.no_song_name,sN);
            remoteViews.setImageViewUri(R.id.no_song_image,songImgPath);

            //设置通知栏的暂停按钮,点击时将发送广播出去
            Intent in=new Intent();
            in.setAction("NOTIFICATION_ISSTOP");
            //sendBroadcast(in);
            PendingIntent pi=PendingIntent.getBroadcast(context,5,in, FLAG_CANCEL_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.no_is_start,pi);


            if(MainActivity.mediaPlayer.isPlaying()){
                Log.e("开始","开始");
                Uri uri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+"://"+getResources().getResourcePackageName(R.drawable.pause)+"/"+getResources().getResourceTypeName(R.drawable.pause)+"/"+getResources().getResourceEntryName(R.drawable.pause));
                remoteViews.setImageViewUri(R.id.no_is_start,uri);
            }else {
                Log.e("暂停","暂停");
                Uri uri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+"://"+getResources().getResourcePackageName(R.drawable.start)+"/"+getResources().getResourceTypeName(R.drawable.start)+"/"+getResources().getResourceEntryName(R.drawable.start));
                remoteViews.setImageViewUri(R.id.no_is_start,uri);
            }
            PendingIntent pendingIntent=PendingIntent.getActivity(context,0,intent, FLAG_CANCEL_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.no_song,pendingIntent);
            notification.contentView=remoteViews;
            notification.contentIntent=pendingIntent;
            notificationManager.notify(1,notification);
        }

        public void setContext(Context context){
            this.context=context;
        }

        public void unRegister(){
            unregisterReceiver(no);
        }
        public void clearNotification(){
            notificationManager.cancel(1);
            Log.e("清除通知栏","清除通知栏");
        }


    }

    public class NotficationStop extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("NOTIFICATION_ISSTOP")){
                if(MainActivity.mediaPlayer.isPlaying()){
                    MainActivity.mediaPlayer.pause();
                    Uri uri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+"://"+getResources().getResourcePackageName(R.drawable.pause)+"/"+getResources().getResourceTypeName(R.drawable.pause)+"/"+getResources().getResourceEntryName(R.drawable.pause));
                    PlayServer.this.remoteViews.setImageViewUri(R.id.no_is_start,uri);
                }else {
                    MainActivity.mediaPlayer.start();
                    Uri uri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+"://"+getResources().getResourcePackageName(R.drawable.start)+"/"+getResources().getResourceTypeName(R.drawable.start)+"/"+getResources().getResourceEntryName(R.drawable.start));
                    remoteViews.setImageViewUri(R.id.no_is_start,uri);
                }
            }
        }
    }

}
